package org.smile.db.sql.page;

import java.sql.SQLException;

import org.smile.util.RegExp;

public class SQLServerDialectPage implements DialectPage {

	private String newSql;
	private String orderby;
	
	public SQLServerDialectPage(String sql) throws SQLException{
		/**
		 * 查的order by 
		 */
		RegExp reg=new RegExp(" order +by ",false); 
		
		int indexEnd=reg.lastIndexEnd(sql);
		
		//最后匹配的结束
		int indexStart=reg.lastIndex(sql);
		//处理后的sql
		newSql=sql;
		if(indexEnd>0){
			orderby=sql.substring(indexEnd,sql.length());
			newSql=sql.substring(0,indexStart);
		}
		if(orderby==null){
			throw new SQLException("请指定排序列名称:此分页方法必须指定排序名,因为此方法中使用了row_number()方法");
		}
		
	}
	public String getCountSql() {
		//条数sql
		return "SELECT COUNT(*) FROM ("+newSql+") COUNT_TABLE_T";
	}
	
	public String getDataSql(int page,int size) {
		int firstRow=(page-1)*size;
		int endRow=firstRow+size;
		//数据sql
		return "SELECT * FROM (SELECT TOP "+endRow+" DATA_TABLE_T.*,ROW_NUMBER() OVER (ORDER BY "+orderby+") ROW_NUM FROM ("+newSql+") DATA_TABLE_T) RESULT_TABLE_T WHERE ROW_NUM>"+firstRow;
		
	}

}
